
package com.joolun.cloud.mall.api.controller;

import cn.hutool.core.util.StrUtil;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.mall.api.service.UserInfoService;
import com.joolun.cloud.mall.api.util.ApiUtil;
import com.joolun.cloud.mall.common.entity.UserInfo;
import com.joolun.cloud.weixin.common.dto.LoginDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;

/**
 * 微信用户
 *
 * @author www.joolun.com
 * @date 2019-08-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wxuser")
@Api(value = "wxuser", tags = "微信用户API")
public class WxUserController {

	private final UserInfoService userInfoService;

	/**
	 * 小程序用户登录
	 * @param request
	 * @param loginDTO
	 * @return
	 */
	@ApiOperation(value = "小程序用户登录")
	@PostMapping("/loginma")
	public R loginMa(HttpServletRequest request, @RequestBody LoginDTO loginDTO){
		try {
			loginDTO.setAppId(ApiUtil.getAppId(request));
			UserInfo userInfo = userInfoService.loginMa(loginDTO);
			//异步更新用户省市
			if(userInfo != null && StrUtil.isNotEmpty(userInfo.getId())){
				CompletableFuture.runAsync(() -> {
					userInfoService.updateProCity(request, userInfo.getId());
				});
			}
			return R.ok(userInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 公众号用户登录
	 * @param loginDTO
	 * @return
	 */
	@ApiOperation(value = "公众号用户登录")
	@PostMapping("/loginmp")
	public R loginMp(HttpServletRequest request, @RequestBody LoginDTO loginDTO){
		try {
			loginDTO.setAppId(ApiUtil.getAppId(request));
			UserInfo userInfo = userInfoService.loginMp(loginDTO, request);
			//异步更新用户省市
			if(userInfo != null && StrUtil.isNotEmpty(userInfo.getId())){
				CompletableFuture.runAsync(() -> {
					userInfoService.updateProCity(request, userInfo.getId());
				});
			}
			return R.ok(userInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}
}
